package com.qf.smsplatform.webmaster.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.smsplatform.webmaster.constans.ResultCode;
import com.qf.smsplatform.webmaster.dto.R;
import com.qf.smsplatform.webmaster.mapper.UserUrlMapper;
import com.qf.smsplatform.webmaster.pojo.TAdminUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class UrlInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper;

    private UserUrlMapper userUrlMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper){
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setUserUrlMapper(UserUrlMapper userUrlMapper){
        this.userUrlMapper = userUrlMapper;
    }

    //前置通知

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录
        TAdminUser user = (TAdminUser) request.getSession().getAttribute("user");
        Long id = user.getId();
        //根据用户的id查询能访问的地址
        List<String> urls = userUrlMapper.findAllUrlsByUserId(id);
        //获取当前访问的地址
        String uri = request.getRequestURI();
        //判断当前访问地址在不在允许访问的范围中
        boolean contains =urls.contains(uri);
        if (!contains){
            R error = R.setError(ResultCode.NOT_ALLOW_ACCESS,"未授权",null);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(error));
        }
        return contains;
    }
}
